package com.ebupt.migu.music.schedule.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xuhongsong@cd.ebupt.com
 * @version 1.0
 * @className FtpUtils
 * @date 2020/7/8 14:44
 */
@Component
@Slf4j
public class FtpUtils {

    private FTPClient ftpClient;

    // 服务器IP地址







    /**
     * @param ip
     * @param port
     * @param userName
     * @param userPwd
     * @param path
     * @throws SocketException
     * @throws IOException function:连接到服务器
     */
    public void connectServer(String ip, int port, String userName, String userPwd, String path) {
        ftpClient = new FTPClient();
        try {
            // 连接
            ftpClient.connect(ip, port);
            // 登录

            ftpClient.login(userName, userPwd);
            ftpClient.enterLocalPassiveMode();
            if (path != null && path.length() > 0) {
                // 跳转到指定目录
                ftpClient.changeWorkingDirectory(path);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @throws IOException function:关闭连接
     */
    public void closeServer() {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param path
     * @return function:读取指定目录下的文件名
     * @throws IOException
     */
    public List<String> getFileList(String path) {
        List<String> fileLists = new ArrayList<String>();
        // 获得指定目录下所有文件名
        FTPFile[] ftpFiles = null;
        try {
            ftpFiles = ftpClient.listFiles(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; ftpFiles != null && i < ftpFiles.length; i++) {
            log.info("该{}目录下第{}个文件，文件名：{}", path, i, ftpFiles[i].getName());
            FTPFile file = ftpFiles[i];
            if (file.isFile()) {
                fileLists.add(file.getName());
            }
        }
        return fileLists;
    }

    /**
     * @param
     * @return function:从服务器上读取指定的文件  fileName
     * @throws ParseException
     * @throws IOException
     */
    public List<String> readFile1(String fileName) throws ParseException {
        InputStream ins = null;
      //  StringBuilder builder = null;
        List<String> list = null;
        try {
            // 从服务器上读取指定的文件
            String strencoding="UTF-8";
            ins = ftpClient.retrieveFileStream(fileName);

            BufferedReader reader = new BufferedReader(new InputStreamReader(ins, strencoding));
            String line;
          //  builder = new StringBuilder(150);
            list=new ArrayList<String>();
            while ((line = reader.readLine()) != null) {
                if(line.trim().length()>2) {
                    list.add(line);
                }
             //   builder.append(line);
            }
            reader.close();
            if (ins != null) {
                ins.close();
            }
            // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
         //  ftpClient.getReply();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<String> readFile(String fileName) {
        InputStream ins = null;
        List<String> refundList = new ArrayList<String>();
        try {
            // 从服务器上读取指定的文件
            ins = ftpClient.retrieveFileStream(fileName);
            if(ins != null){
                BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
                String line = "";
                while ((line = reader.readLine()) != null) {
                    refundList.add(line);
                }
                System.out.println("list.size:"+refundList.size());
                reader.close();
                ins.close();
                ftpClient.completePendingCommand();
                // 主动调用一次getReply()把接下来的226消费掉. 这样做是可以解决这个返回null问题
             //   ftpClient.getReply();
                return  refundList;
            }else {
                System.out.println("读取ftp文件不存在");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return refundList;
    }

    /**
     * @param fileName function:删除文件
     */
    public void deleteFile(String fileName) {
        try {
            ftpClient.deleteFile(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

  /*  public static void main(String[] args) {
        FtpUtils ftpUtils=new FtpUtils();
        ftpUtils.connectServer("218.200.160.122",21,"wxtk","pyZx2{g0", "/fine-operation/msg/");
        List<String> list=ftpUtils.getFileList("/fine-operation/msg/");
        for (String s:list) {
            System.out.println(s);
        }
    }
*/
}
